package com.example.petgrowing;


import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends AppCompatActivity {

    public static final String TAG = "pet-mainactivity";
    public EditText editAccount;
    public EditText editPassword;
    public Button btnlogin;
    public Button btnregister;
    public DBHelper dbHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new DBHelper(MainActivity.this);
        btnregister = findViewById(R.id.btn_register);
        btnlogin = findViewById(R.id.btn_login);
        editAccount = findViewById(R.id.userAccount);
        editPassword = findViewById(R.id.userPassword);

        btnregister.setOnClickListener(view -> {
            Intent intent = new Intent(getApplicationContext(),activity_register.class);
            startActivity(intent);
        });

        btnlogin.setOnClickListener(view -> {
            String useraccount = editAccount.getText().toString();
            String userpassword = editPassword.getText().toString();
            Cursor cursor = dbHelper.getReadableDatabase().query("user", null, "userAccount=?", new String[]{useraccount}, null, null, null);
            ArrayList<Map<String, String>> resultlist = new ArrayList<Map<String, String>>();
            String dbpassword = null;

            while (cursor.moveToNext()) {
                Map<String, String> map = new HashMap<>();
                map.put("UserAccount", cursor.getString(0));
                map.put("UserPassword", cursor.getString(2));
                resultlist.add(map);

                dbpassword = map.get("UserPassword");
            }

            if (resultlist == null || resultlist.size() == 0) {
                Toast.makeText(MainActivity.this, "未查询到用户信息或者账号输入错误，请先注册", Toast.LENGTH_SHORT).show();
                editAccount.setText("");
                editPassword.setText("");
            } else if (userpassword.equals(dbpassword)) {
                Toast.makeText(MainActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
                startActivity(intent);
            }
            else if(TextUtils.isEmpty(userpassword)){
                Toast.makeText(MainActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();

            }
            else{
                Toast.makeText(MainActivity.this,"密码错误,请重新输入",Toast.LENGTH_SHORT).show();
                editPassword.setText("");
            }
        });

    }
}
